<?php
class Application_Model_KeywordMapper
{
	protected $_dbTable;
	
	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}

	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_Keyword');
		}
		return $this->_dbTable;
	}

	public function save(Application_Model_Blog $blog)
	{
		$data = array(
            'keyword'   => $blog->getKeyword(),
            'blogId'    => $blog->getId(),
		);
        $keyword_obj = $this->getDbTable()->fetchAll();
        $keyword_arr = array();
        $blogKeyword = new Application_Model_DbTable_BlogKeyword();
        foreach ($keyword_obj as $row) {
            $keyword_arr[$row->keyword] = array("id"=>$row->id, "count"=>$row->count);
        }
        foreach ($data['keyword'] as $keyword)
        {
		    if (!(array_key_exists($keyword, $keyword_arr))) {
                $tmp = array(
                    'keyword' => $keyword,
                    'count'   => 1,
                );
                $keywordId = $this->getDbTable()->insert($tmp);
                unset($tmp);
                $tmp = array(
                    'blog_id'    => $data['blogId'],
                    'keyword_id' => $keywordId,
                );
                $blogKeyword->insert($tmp);
		    } else {
                $tmp = array(
                    'keyword' => $keyword,
                );
                $tmp['count'] = $keyword_arr[$keyword]['count'] + 1;
			    $this->getDbTable()->update($tmp, array('id = ?' => $keyword_arr[$keyword]['id']));
                unset($tmp);
                $tmp = array(
                    'blog_id'    => $data['blogId'],
                    'keyword_id' => $keyword_arr[$keyword]['id'],
                );
                $blogKeyword->insert($tmp);
            }
        }
	}
	
    public function fetchAll()
    {
        $resultBlog = $this->getDbTable()->fetchAll(null, "id DESC");
        $entries   = array();
        foreach ($resultBlog as $row) {
            $entry = new Application_Model_Blog();
            $entry->setId($row->id)
                  ->setKeyword($row->keyword);
            $entries[] = $entry;
        }
        return $entries;
    }
}
